package com.ews.onlineexchange.service;

import java.util.Date;

import javax.enterprise.context.ConversationScoped;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.inject.Named;

import com.ews.onlineexchange.dao.ProfessionUserDao;
import com.ews.onlineexchange.model.ProfessionUser;
import com.ews.onlineexchange.model.QualificationCert;
import com.ews.onlineexchange.model.RejectRecord;
import com.ews.onlineexchange.model.User;
import com.ews.onlineexchange.service.qualifier.MessagePushWsEvent;
import com.ews.onlineexchange.service.qualifier.SupplierCertAuditFailEvent;

@Named
@ConversationScoped
public class CertHome extends EntityHome<QualificationCert, String> {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	@Inject
	RejectRecordHome rejectRecordHome;
	@Inject
	UserService userService;
	@Inject
	ProfessionUserDao professionUserDao;
	public String audit() {
		getInstance().setProfessionUser(getLoginedProfessionUser());
		getInstance().setAuditResult(true);
		getInstance().setValid(true);
		getInstance().setAuditTime(new Date());
		String result = super.saveAndFlush();
		if (result.equals("saved")) {
			//中介资质审核成功消息推送
			String pushMessage = messgaePushService.addCertAuditSuccessSupplier(getInstance());
			messagePushWsEvent.fire(pushMessage);
			return "ok";
		}
			
		return null;
	}
	
	
	
	public String reSubmit() {
		getInstance().setAuditTime(null);
		getInstance().setProfessionUser(null);
		getInstance().setAuditResult(null);
		getInstance().setValid(false);
		getInstance().setCurrRejectRecord(null);
		return super.saveAndFlush();
	}
	
	@Inject
	@MessagePushWsEvent
	Event<String> messagePushWsEvent;
	
	@Inject
	MessgaePushService messgaePushService;
	
	@Inject
	@SupplierCertAuditFailEvent
	Event<QualificationCert> supplierCertAuditFailEvent;
	
	public String reject() {
		getInstance().setAuditTime(new Date());
		getInstance().setProfessionUser(getLoginedProfessionUser());
		getInstance().setAuditResult(false);
		getInstance().setValid(false);
		RejectRecord rejectRecord = rejectRecordHome.getInstance();
		rejectRecord.setRejectTime(new Date());
		getInstance().setCurrRejectRecord(rejectRecord);
		getInstance().getHistoryRejectRecords().add(rejectRecord);
		
		String result = super.saveAndFlush();
		if (result.equals("saved")) {
			String pushMessage = messgaePushService.addCertRejectSupplier(getInstance());
			messagePushWsEvent.fire(pushMessage);
			supplierCertAuditFailEvent.fire(getInstance());
			return "ok";
		}
			
		return null;
	}
	
	public ProfessionUser getLoginedProfessionUser() {
		User user = userService.getLoginedUser();
		return professionUserDao.find(user.getId());
	}
}
